package com.ht.pms.core.dao.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.ht.pms.core.dto.QueryFileLogReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.ht.pms.core.dao.SalaryUploadFileLogDao;
import com.ht.pms.core.dto.upload.UploadFileLog;

@Repository
public class SalaryUploadFileLogDaoImpl implements SalaryUploadFileLogDao {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public void insertUploadFileLog(List<UploadFileLog> fileLogs, int ver) {
		
		String sql = "insert into t_upload_file_log(file_id, batch_code, dict_code, job_code,  code, msg, content, version) values(?, ?, ?, ?, ?, ?, ?, ?)";
		jdbcTemplate.batchUpdate(sql , new BatchPreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setInt(1, fileLogs.get(i).getFileId());
				ps.setString(2, fileLogs.get(i).getBatchCode());
				ps.setString(3, fileLogs.get(i).getDictCode());
				ps.setString(4, fileLogs.get(i).getJobCode());
				ps.setString(5, fileLogs.get(i).getCode());
				ps.setString(6, fileLogs.get(i).getMsg());
				ps.setString(7, fileLogs.get(i).getContent());
				ps.setInt(8, ver);
			}

			@Override
			public int getBatchSize() {
				return fileLogs.size();
			}
			
		});
	}

	@Override
	public List<UploadFileLog> getUploadFileLog(QueryFileLogReq req) {
		String sql = "SELECT * FROM t_upload_file_log l WHERE " +
				"l.file_id = '"+req.getFileId()+"' AND l.version = ( SELECT max(version) FROM t_upload_file_log t WHERE t.file_id = '"+req.getFileId()+"') " +
				"AND l.is_repair = 0 LIMIT "+(req.getPage()-1)*req.getLimit()+","+req.getLimit()+"";
		return jdbcTemplate.query(sql,new BeanPropertyRowMapper<UploadFileLog>(UploadFileLog.class));
	}

	@Override
	public int getUploadFileLogCount(QueryFileLogReq req) {
		String sql = "SELECT count(*) as count FROM t_upload_file_log l WHERE l.file_id = '"+req.getFileId()+"' AND l.version = ( SELECT max(version) FROM t_upload_file_log t WHERE t.file_id = '"+req.getFileId()+"') AND l.is_repair = 0" ;
		Map<String,Object> result = jdbcTemplate.queryForMap(sql);
		int count = 0;
		if(result != null){
			count = Integer.parseInt(result.get("count")+"");
		}
		return count;
	}

	@Override
	public List<UploadFileLog> selectUploadFileLogByFileId(Integer fileId) {
		String sql = "SELECT * FROM t_upload_file_log WHERE file_id = ? ORDER BY version desc";
		return jdbcTemplate.query(sql, new Object[] {fileId}, new BeanPropertyRowMapper<UploadFileLog>(UploadFileLog.class));
	}

}
